package com.kly.cashmall.module.products;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.google.firebase.analytics.FirebaseAnalytics;
import com.kly.cashmall.AppApplication;
import com.kly.cashmall.R;
import com.kly.cashmall.base.BaseBarActivity;
import com.kly.cashmall.base.app_action.BaseActionHelper;
import com.kly.cashmall.bean.BorrowCashPeriod;
import com.kly.cashmall.bean.ProductDetailBean;
import com.kly.cashmall.bean.ProductSubmitFilterBean;
import com.kly.cashmall.bean.ProductCategoryBean;
import com.kly.cashmall.bean.UserProfileListBean;
import com.kly.cashmall.event.FirebaseAnalyticsEvent;
import com.kly.cashmall.framework.mvp.PresenterLifeCycle;
import com.kly.cashmall.module.products.adapter.ProductDetailAmountAdapter;
import com.kly.cashmall.module.products.adapter.ProductDetailDurationAdapter;
import com.kly.cashmall.module.products.presenter.ProductDetailPresenter;
import com.kly.cashmall.module.products.presenter.ProductDetailViewer;
import com.kly.cashmall.module.profile.adapter.ProfileListAdapter;
import com.kly.cashmall.popup.ErrorMsgPopup;
import com.kly.cashmall.popup.OrganizationDetailsPopup;
import com.kly.cashmall.utils.function.CommonUtils;
import com.kly.cashmall.utils.function.GlideUtils;
import com.kly.cashmall.utils.data.TextUtil;
import com.kly.cashmall.utils.function.ToastUtil;

import java.util.List;

/**
 * @author
 */
public class ProductDetailActivity extends BaseBarActivity implements ProductDetailViewer {

    private static final String CATEGORYCODE = "categoryCode";
    private static final String MERCHANTCODE = "merchantCode";

    private String productCode = "";

    private ProfileListAdapter mProductAdapter;

    private String mCategoryCode;
    private List<BorrowCashPeriod> periodList;

    @PresenterLifeCycle
    ProductDetailPresenter presenter = new ProductDetailPresenter(this);
    private RecyclerView mAmountSelectList;
    private List<ProductDetailBean> borrowCashList;
    private RecyclerView mDurationSelectList;
    private ProductDetailDurationAdapter mDateAdapter;
    private ProductDetailAmountAdapter mAmountAdapter;
    private boolean initialDuration = false;
    private boolean firstDayCheck = false;
    private int lastAmountCheck = 0;
    private String mMerchantCode;
    private boolean permitApply;
    private boolean buttonJumpEnabled;
    private String buttonMsg;

    public static Intent newIntent(Context context, String categoryCode, String merchantCode) {
        Intent intent = new Intent(context, ProductDetailActivity.class);
        intent.putExtra(CATEGORYCODE, categoryCode);
        intent.putExtra(MERCHANTCODE, merchantCode);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }


    @Override
    protected void setView(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_loan_product_detail);
        setTitle(this.getResources().getString(R.string.details));
        FirebaseAnalytics.getInstance(AppApplication.getInstance()).logEvent(FirebaseAnalyticsEvent.Product_Details_Into,new Bundle());
        mCategoryCode = getIntent().getStringExtra(CATEGORYCODE);
        mMerchantCode = getIntent().getStringExtra(MERCHANTCODE);

        init();
    }

    private void init() {
        mAmountSelectList = bindView(R.id.amount_select_list);
        mAmountAdapter = new ProductDetailAmountAdapter();
        mAmountSelectList.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mAmountSelectList.setAdapter(mAmountAdapter);
        mAmountSelectList.setNestedScrollingEnabled(false);

        mDurationSelectList = bindView(R.id.duration_select_list);
        mDurationSelectList.setNestedScrollingEnabled(false);
        mDateAdapter = new ProductDetailDurationAdapter();
        mDurationSelectList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mDurationSelectList.setAdapter(mDateAdapter);


        mAmountAdapter.setOnItemClickListener((adapter, view, position) -> {
            initialDuration = false;
            for (int j = 0; j < borrowCashList.size(); j++) {
                if (position == j) {
                    borrowCashList.get(j).setChecked(true);
                    periodList = borrowCashList.get(j).getBorrowCashPeriods();
                    mDateAdapter.setList(periodList);
                    for (int k = 0; k < periodList.size(); k++) {
                        if (periodList.get(k).checked) {
                            productCode = periodList.get(k).productCode;
                            initialDuration = true;
                        }
                    }
                } else {
                    borrowCashList.get(j).setChecked(false);
                }
            }
            if (!initialDuration) {
                periodList.get(0).setChecked(true);
                productCode = periodList.get(0).productCode;
            }
            mAmountAdapter.notifyDataSetChanged();
        });
        mDateAdapter.setOnItemClickListener((adapter, view, position) -> {
                for (int j = 0; j < periodList.size(); j++) {
                    if (position == j) {
                        periodList.get(j).setChecked(true);
                        productCode = periodList.get(j).productCode;
                    } else {
                        periodList.get(j).setChecked(false);
                    }
                }
                mDateAdapter.notifyDataSetChanged();

        });
        RecyclerView mPreferredListRecycler = bindView(R.id.auth_info_list);
        mProductAdapter = new ProfileListAdapter();
        mPreferredListRecycler.setNestedScrollingEnabled(false);
        mPreferredListRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        mPreferredListRecycler.setAdapter(mProductAdapter);

        mProductAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (mProductAdapter.getItem(position).isEnableToClick()) {
                BaseActionHelper.with(this).handleAction(mProductAdapter.getItem(position).getJumpUrl());
            } else {
                if (!TextUtil.isEmpty(mProductAdapter.getItem(position).getDisableText())) {
                    ToastUtil.showToast(mProductAdapter.getItem(position).getDisableText());
                }
            }
        });
    }

    @Override
    protected void loadData() {
        presenter.getProductDetail(mCategoryCode,mMerchantCode);
    }

    @Override
    public void setProductDetail(ProductCategoryBean productCategory) {
        GlideUtils.loadImage(this,productCategory.categoryLogo,bindView(R.id.iv_product_logo));
        bindText(R.id.tv_product_name, productCategory.categoryName);
        bindText(R.id.tv_product_tips, productCategory.categoryDesc);
        bindText(R.id.product_tip, productCategory.reminderTips);
        bindText(R.id.tv_auth_tips,"Profile ("+ productCategory.categoryName +" Required)");
        if (!TextUtil.isEmpty(productCategory.companyName)){
            bindView(R.id.company_container,true);
            bindText(R.id.tv_company_name, productCategory.companyName);
            ((TextView) bindView(R.id.tv_company_name)).getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );
            bindView(R.id.tv_company_name,v -> {
                BaseActionHelper.with(this).handleAction(productCategory.companyUrl);
            });

            OrganizationDetailsPopup popup = new OrganizationDetailsPopup(this);
            popup.setOutSideDismiss(false);
            popup.setBackPressEnable(false);
            popup.setPopupGravity(Gravity.CENTER).showPopupWindow();
            String tip = "Loan Provide By:\n"+productCategory.companyName;
            popup.setTitleText(CommonUtils.setHighLight(tip,productCategory.companyName, ContextCompat.getColor(this,R.color.color_FE4F12)));
            popup.setUrlText(productCategory.companyUrl);
            popup.setConfirmText(getString(R.string.yes_i_know));
            popup.setConfirmClick(view1 -> {
                popup.dismiss();
            });
            popup.setUrlClick(view1 -> {
                BaseActionHelper.with(this).handleAction(productCategory.companyUrl);
                popup.dismiss();
            });
        }else {
            bindView(R.id.company_container,false);
        }

        buttonMsg = productCategory.getButtonMsg();
        if (!TextUtil.isEmpty(buttonMsg)){
            bindText(R.id.tv_next,buttonMsg);
        }
        borrowCashList = productCategory.borrowCashList;

        for (int i = 0; i < borrowCashList.size(); i++) {
            if (!borrowCashList.get(i).locked) {
                lastAmountCheck = i;
            }
        }
        borrowCashList.get(lastAmountCheck).setChecked(true);
        mAmountAdapter.setList(borrowCashList);
        periodList = productCategory.getBorrowCashList().get(lastAmountCheck).getBorrowCashPeriods();
        for (int i = 0; i < periodList.size(); i++) {
            if (!firstDayCheck) {
                if (!periodList.get(i).locked) {
                    firstDayCheck = true;
                    periodList.get(i).setChecked(true);
                    productCode = periodList.get(i).productCode;
                }
            }
        }
        mDateAdapter.setList(periodList);
        permitApply = productCategory.isPermitApply();
        bindEnable(R.id.tv_next, permitApply && buttonJumpEnabled);

    }


    @Override
    public void setUserProfileList(UserProfileListBean userProfileListBean) {
        bindView(R.id.profile_list, true);
        mProductAdapter.setList(userProfileListBean.getActions());
        buttonJumpEnabled = userProfileListBean.buttonJumpEnabled;
        bindEnable(R.id.tv_next, buttonJumpEnabled);
        if (TextUtil.isEmpty(buttonMsg)){
            bindText(R.id.tv_next,buttonMsg);
        }

        bindView(R.id.tv_next, view -> {
            FirebaseAnalytics.getInstance(AppApplication.getInstance()).logEvent(FirebaseAnalyticsEvent.Product_Details_Filter_Click,new Bundle());
            presenter.getOrderSubmitFilter(productCode,mMerchantCode);
        });
    }


    @Override
    public void getOrderSubmitPostSuccess(ProductSubmitFilterBean filterBean) {
        BaseActionHelper.with(getActivity()).handleAction(filterBean.getJumpUrl());
        finish();
    }

    @Override
    public void getOrderSubmitPostFail(String message) {
        ErrorMsgPopup popup = new ErrorMsgPopup(getActivity());
        popup.setContent(message);
        popup.setPopupGravity(Gravity.CENTER).showPopupWindow();
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.getUserProfileList(mCategoryCode,mMerchantCode);
    }
}
